package com.babyqiao.wallpaper.manager.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.babyqiao.wallpaper.manager.service.OssService;
import com.babyqiao.wallpaper.manager.utils.common.ConstandPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author qinglongzhai
 * @date 2020/12/08
 */
@Service
public class OssServiceImpl implements OssService {
    /**
     * 上传封面到OSS
     */
    @Override
    public String uploadFileCover(MultipartFile file) {
        String endpoint = ConstandPropertiesUtils.END_POINT;
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstandPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstandPropertiesUtils.KEY_SECRET;
        String bucketName = ConstandPropertiesUtils.BUCKET_NAME;
        String prefix=ConstandPropertiesUtils.PREFIX;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件流。
            InputStream inputStream = file.getInputStream();
            //获取文件名称。
            String originalFilename = file.getOriginalFilename();

            //获取UUID
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //拼接出文件名
            originalFilename = uuid + originalFilename;

            //获取当前日期
            String dataPath = new DateTime().toString("yyyyMMdd");
            //拼接出最终文件名
            originalFilename = prefix+"/"+ dataPath + "/" + originalFilename;

            //调用OSS方法实现上传。
            ossClient.putObject(bucketName, originalFilename, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //拼接返回路径

            //https://zql-wallpaper.oss-cn-beijing.aliyuncs.com/
            String url = "https://" + bucketName + "." + endpoint + "/" + originalFilename;
            return url;


        } catch (Exception e) {

        }


        return null;
    }
}
